//
//  XKQRCoderController.m
//  xk100
//
//  Created by xiaokang on 2017/6/21.
//  Copyright © 2017年 xiaokang. All rights reserved.
//

#import "XKQRCoderController.h"
#import <UShareUI/UShareUI.h>
//#import<AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>

@interface XKQRCoderController ()

@property (nonatomic, strong) UIView        *backgroundView;
@property (nonatomic, strong) UIImageView   *iconImageView;
@property (nonatomic, strong) UILabel       *userNameLabel;
@property (nonatomic, strong) UILabel       *userLocationLabel;
@property (nonatomic, strong) UILabel       *timeLabel;
@property (nonatomic, strong) UIImageView   *qrCoderImageView;
@property (nonatomic, strong) UILabel       *descriptionLabel;

@end

@implementation XKQRCoderController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initShareButton];
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark - 设置分享按钮
- (void)initShareButton {
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"account_share"] style:UIBarButtonItemStylePlain target:self action:@selector(shareTypeSelected)];
    self.navigationItem.rightBarButtonItem = item;
}

- (void)setQr_base_url:(NSString *)qr_base_url {
    _qr_base_url = qr_base_url;
}

#pragma mark - 初始换控件
- (void)initSubViews {
    self.navigationItem.title = @"我的二维码";
    self.view.backgroundColor = [UIColor yg_colorWithHexString:@"#303030"];
    
    _backgroundView = [UIView new];
    _backgroundView.backgroundColor = [UIColor yg_colorWithHexString:@"#ffffff"];
    _backgroundView.layer.cornerRadius = 4;
    _backgroundView.layer.masksToBounds = YES;
    _backgroundView.layer.shadowColor = [UIColor blackColor].CGColor;
    [self.view addSubview:_backgroundView];
    [_backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(Main_Width*0.9, Main_Height*0.7));
        make.center.mas_equalTo(self.view);
    }];
    
    
    _iconImageView = [[UIImageView alloc] init];
    _iconImageView.image = [[UIImage appIconImage] imageWithCornerRadius:4];
    [_backgroundView addSubview:_iconImageView];
    [_iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(_backgroundView).offset(20*Scale_W);
        make.size.mas_equalTo(CGSizeMake(60*Scale_W, 60*Scale_W));
    }];
    
//    _iconImageView.layer.shadowOpacity = 0.8f;
//    _iconImageView.layer.shadowRadius = 4.f;
//    _iconImageView.layer.shadowOffset = CGSizeMake(4,4);
    
    _userNameLabel = [[UILabel alloc] init];
    _userNameLabel.font = [UIFont boldSystemFontOfSize:18];
    _userNameLabel.text = [UserDefaults objectWithKey:@"name"];
    _userNameLabel.textColor = [UIColor blackColor];
    [_backgroundView addSubview:_userNameLabel];
    [_userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_iconImageView.mas_right).offset(12*Scale_W);
        make.top.mas_equalTo(_iconImageView);
        make.height.mas_equalTo(_iconImageView.mas_height).multipliedBy(0.5);
    }];
    
    //    [UserDefaults setObject:placeMark.country withKey:@"current_country"]; // 国家
    //    [UserDefaults setObject:placeMark.locality withKey:@"current_locality"]; // 城市
    //    [UserDefaults setObject:placeMark.subLocality withKey:@"current_subLocality"]; // 街区
    //    [UserDefaults setObject:placeMark.subLocality withKey:@"current_name"]; // 详细地址
    
    NSString *location = [NSString stringWithFormat:@"%@ %@",[UserDefaults objectWithKey:@"current_locality"],[UserDefaults objectWithKey:@"current_subLocality"]];
    if (IsEmptyStr(location)) {
        location = @"未知位置";
    }
    _userLocationLabel = [UILabel getLabWithText:location textFont:Font_15 textColor:[UIColor grayColor]];
    [_backgroundView addSubview:_userLocationLabel];
    [_userLocationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.left.mas_equalTo(_userNameLabel);
        make.bottom.mas_equalTo(_iconImageView);
    }];
    
    
    NSString *timeString = [[NSDate date] yyyy_MM_dd_string];
    _timeLabel = [UILabel getLabWithText:timeString textFont:Font_10 textColor:[UIColor grayColor]];
    [_backgroundView addSubview:_timeLabel];
    [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_userNameLabel);
        make.right.mas_equalTo(_backgroundView).offset(-20*Scale_W);
    }];
    
    
    
    NSString *temp = [NSString stringWithFormat:@"%@?uid=",_qr_base_url];
    NSString *url = [NSString stringWithFormat:@"%@%@",[_qr_base_url isValidUrl] ? temp : @"https://www.xiaokang100.com/shop/index.php?act=login&op=register&member_id=",[UserDefaults objectWithKey:@"uid"]];
    UIImage *image = [[UIImage appIconImage] imageWithBorderWith:4 borderColor:[UIColor whiteColor] cornerRadius:2];
    _qrCoderImageView = [[UIImageView alloc] init];
    _qrCoderImageView.image = [UIImage qrImageWithString:url
                                             qrImageSize:500
                                               logoImage:image
                                                logoSize:120];
    [_backgroundView addSubview:_qrCoderImageView];
    
//    _qrCoderImageView.layer.shadowOpacity = 0.8f;
//    _qrCoderImageView.layer.shadowRadius = 4.f;
//    _qrCoderImageView.layer.shadowOffset = CGSizeMake(4,4);
    
    [_qrCoderImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_iconImageView.mas_bottom).offset(20*Scale_W);
        make.left.mas_equalTo(_backgroundView).offset(30*Scale_W);
        make.right.mas_equalTo(_backgroundView).offset(-30*Scale_W);
        make.height.mas_equalTo(Main_Width*0.9-60*Scale_W);
    }];
    
    _descriptionLabel = [UILabel getLabWithText:@"分享创业快乐  共享小康幸福\n\n扫一扫上面的二维码,加入到我的队伍中来吧!" textFont:Font_13 textColor:[UIColor grayColor] textAlignment:NSTextAlignmentCenter numberOfLines:0];
    [_backgroundView addSubview:_descriptionLabel];
    [_descriptionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_backgroundView).offset(20*Scale_W);
        make.right.mas_equalTo(_backgroundView).offset(-20*Scale_W);
        make.bottom.mas_equalTo(_backgroundView).offset(-20*Scale_W);
    }];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shareTypeSelected)];
    [_backgroundView addGestureRecognizer:tap];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(saveQRCoderImage:)];
    [_backgroundView addGestureRecognizer:longPress];
    
    
}

#pragma mark -
- (void)saveQRCoderImage:(UILongPressGestureRecognizer *)sender {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:@"保存二维码截图到相册" preferredStyle:UIAlertControllerStyleActionSheet];
    @weakify(self);
    UIAlertAction *action_save = [UIAlertAction actionWithTitle:@"保存到相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        [self saveImageToAlbum:[_backgroundView yg_screenshot]];
    }];
    [alertVC addAction:action_save];
    
    UIAlertAction *action_cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:action_cancel];
    
    [self presentViewController:alertVC animated:YES completion:^{
        
    }];
    
}

// 分享类型选择 1:链接  2:二维码
- (void)shareTypeSelected {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    @weakify(self);
    UIAlertAction *action_qrcode = [UIAlertAction actionWithTitle:@"分享邀请链接" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        [self share:1];
    }];
    [alertVC addAction:action_qrcode];
    
    
    UIAlertAction *action_url = [UIAlertAction actionWithTitle:@"分享二维码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        [self share:2];
    }];
    [alertVC addAction:action_url];
    
    UIAlertAction *action_cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:action_cancel];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}



#pragma mark - share
- (void)share:(NSUInteger)type {
    //显示分享面板
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        if (type == 1) {
            [self shareWebPageToPlatformType:platformType];
        } else if (type == 2) {
            [self shareImageToPlatformType:platformType];
        }
    }];
}


// 连接分享
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType {
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];

    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"小康100商城" descr:@"购物工厂价、注册送种子、推荐赚种子!" thumImage:[UIImage imageNamed:@"share_logo_icon"]];
    
    //设置网页地址
    NSString *sharedUrl = [NSString stringWithFormat:@"https://jiaoyi.xiaokang100.com/Home/Extension/index?uid=%@",[UserDefaults objectWithKey:@"uid"]];;
    shareObject.webpageUrl = sharedUrl;
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;

    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);

            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }

    }];
}
//
//
//// 文本分享
//- (void)shareTextToPlatformType:(UMSocialPlatformType)platformType
//{
//    //创建分享消息对象
//    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
//    //设置文本
//    messageObject.text = @"社会化组件UShare将各大社交平台接入您的应用，快速武装App。";
//
//    //调用分享接口
//    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
//        if (error) {
//            NSLog(@"************Share fail with error %@*********",error);
//        }else{
//            NSLog(@"response data is %@",data);
//        }
//    }];
//}


// 图片分享
- (void)shareImageToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建图片内容对象
    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
    //如果有缩略图，则设置缩略图
    //    shareObject.thumbImage = [UIImage imageNamed:@"iphone_app"];
    [shareObject setShareImage:[_backgroundView yg_screenshot]];
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}


//// 图文混合分享仅支持新浪微博 (QQ和微信,只允许单独分享)
//- (void)shareImageAndTextToPlatformType:(UMSocialPlatformType)platformType
//{
//    //创建分享消息对象
//    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
//
//    //设置文本
//    messageObject.text = @"社会化组件UShare将各大社交平台接入您的应用，快速武装App。";
//
//    //创建图片内容对象
//    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
//    //如果有缩略图，则设置缩略图
//    shareObject.thumbImage = [UIImage imageNamed:@"icon"];
//    [shareObject setShareImage:@"https://www.umeng.com/img/index/demo/1104.4b2f7dfe614bea70eea4c6071c72d7f5.jpg"];
//
//    //分享消息对象设置分享内容对象
//    messageObject.shareObject = shareObject;
//
//    //调用分享接口
//    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
//        if (error) {
//            NSLog(@"************Share fail with error %@*********",error);
//        }else{
//            NSLog(@"response data is %@",data);
//        }
//    }];
//}





- (void)saveImageToAlbum:(UIImage *)image {
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        //无权限 引导去开启
        [UIAlertController showAlertView:self title:@"未获得相册访问权限!" message:@"" cancelButtonTitle:@"取消" confirmBtnTitle:@"去授权" cancleBlock:^{
            
        } confirmBlock:^{
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if (SYSTEM_VERSION_LESS_THAN(@"10")) {
                [[UIApplication sharedApplication] openURL:url];
            } else {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
            }
        }];
    } else {
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
    if (error) {
        
    } else {
        [SVProgressHUD showSuccessWithStatus:@"保存成功!"];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
